<template>
  <div>
    <div class="like">
      <van-icon
        name="like"
        size="30"
        @click="like"
        :color="iflike ? 'red' : 'gray'"
        :text="iflike ? '已收藏' : '收藏'"
      />
      <span v-if="iflike">已收藏</span>
      <span v-else>收藏</span>
    </div>
  </div>
</template>

<script>
import state, { mapState } from "vuex";
export default {
  computed: {
    ...mapState("user", ["loginStatus", "userInfo"]),
    ...mapState("artical", ["gocollect"]),
  },
  data() {
    return {
      likeColor: `${this.iflike} ? 'red' : 'gray'`,
      detailsid: "",
      iflike: false,
      iscollect: "收藏",
    };
  },
  methods: {
    //初始化页面时判断是否已收藏，向后端请求获取一下收藏列表
    init() {
      let userid = this.userInfo.userid;
      let url = `/users/usercollect?userid=${userid}`;
      console.log(userid, url);
      this.axios
        .get(url)
        .then(res => {
          console.log(res);
          //请求成功后执行函数
          if (res.status === 200) {
            console.log(JSON.parse(res.data[0].likeList));
            let likeList = JSON.parse(res.data[0].likeList);
            likeList.forEach(item => {
              if (item == this.gocollect) {
                this.iflike = true;
              }
            });
          } else {
            console.log("err");
          }
        })
        .catch(err => {
          //请求错误后执行函
          console.log("请求错误");
        });
    },

    //点击收藏事件，向后台数据库插入一条新数据
    like() {
      this.detailsid = this.gocollect;
      let b = this.detailsid;
      let params = `pid=${b}&userid=${this.userInfo.userid}`;
      this.axios
        .post("/users/updatecollect", params)
        .then(res => {
          //请求成功后执行函数
          console.log(res);
          if (res.status == 200) {
            this.iflike = !this.iflike;
          } else {
            console.log("err");
          }
        })
        .catch(err => {
          //请求错误后执行函
          console.log("请求错误");
        });
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="scss" scoped>
.like {
  display: flex;
  flex-direction: column;
  text-align: center;
  span {
    font-size: 12px;
  }
}
</style>
